package org.bt.auth.controller;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.bt.auth.entity.User;
import org.bt.auth.mapper.UserMapper;
import org.bt.common.constant.CommonConstant;
import org.bt.common.entity.Response;
import org.bt.common.utils.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


/**
 * @author zwj
 */
@RestController
@RequestMapping(value = "/login", headers = {CommonConstant.ApiVersion.VERSION_V1})
@Api(tags = "登录")
public class LoginController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    /**
     * Base64编码
     */
    private static final java.util.Base64.Encoder ENCODER = java.util.Base64.getEncoder();

    /**
     * Base64解码
     */
    private static final java.util.Base64.Decoder DECODER = java.util.Base64.getDecoder();

    @PostMapping
    @ApiOperation(value = "登录")
    public Response<?> doLogin(@RequestBody Map<String, String> map) {
        String priKey = redisTemplate.opsForValue().get(CommonConstant.RedisKey.SERVER_PRI_KEY);
        if (StringUtils.isNotBlank(priKey)) {
            String msg = RsaUtil.decrypt(map.get("rsaKey"), priKey);
            if (StringUtils.isNotBlank(msg)) {
                JSONObject json = JSONObject.parseObject(msg);
                String username = json.getString("username");
                String password = json.getString("password");
                User user = userMapper.getUserByUsername(username);
                if (user != null) {
                    if (user.getAvailable() == 0) {
                        return new Response<>().error("当前用户状态不可用");
                    }
                    if (user.getPassword().equals(ENCODER.encodeToString(SmUtil.sm3WithSalt(DECODER.decode(user.getSalt())).digest(password)))) {
                        Map map1 = JSON.parseObject(JSONUtil.parseObj(user).toString(), Map.class);
                        StpUtil.login(user.getId(), new SaLoginModel().setExtraData(map1));
                        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                        return new Response<>().data(tokenInfo, "登录成功");
                    }
                    return new Response<>().error("密码错误");
                }
                return new Response<>().error("用户不存在");
            }
        }
        return new Response<>().error("登录失败");
    }

    @GetMapping("/publicKey")
    @ApiOperation(value = "获取公钥")
    public String publicKey() {
        return redisTemplate.opsForValue().get(CommonConstant.RedisKey.SERVER_PUB_KEY);
    }
}
